package com.stormrage.edu.ctrl.acct;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.stormrage.constants.ErrCons;
import com.stormrage.edu.serv.adm.AdmAcctServ;
import com.stormrage.entity.adm.AdmAcct;
import com.stormrage.entity.adm.AdmRes;
import com.stormrage.entity.adm.req.AdmAcctReq;
import com.stormrage.entity.adm.req.PassReq;
import com.stormrage.entity.rep.ErrorRep;
import com.stormrage.entity.shiro.ShiroAcct;
import com.stormrage.shiro.bind.CurrentUser;
import com.stormragetech.core.ctrl.BaseCtrl;
import com.stormragetech.core.exception.StormrageTechException;
import com.stormragetech.core.util.SecureUtil;

/**
 * @author www.stormragetech.com
 * @date 2016年1月19日
 * @version 1.0.0
 */
@Controller
@RequestMapping("/user")
public class AcctCtrl extends BaseCtrl {

	private static final Logger logger = LoggerFactory.getLogger(AcctCtrl.class);

	@Value("#{constants['html.title']}")
	private String htmlTitle;

	@Value("#{constants['login.title']}")
	private String loginTitle;

	@Autowired
	private AdmAcctServ acctServ;

	@RequestMapping(value = "/registration", method = RequestMethod.GET)
	public String registration(Model model) {

		logger.debug(" 【 Controller 】- 【 AcctCtrl 】- 【 Registration 】-【 GET/POST 】- 开始运行  ");

		try {

			// ------------------ 获取菜单 ------------------

			model.addAttribute("htmlTitle", htmlTitle);

		} catch (Exception e) {
			model.addAttribute("err", e.getMessage());
			return "error/500";
		}
		return "user/registration";
	}

	@RequestMapping(value = "/registration", method = RequestMethod.POST)
	public String registration(AdmAcctReq req, RedirectAttributes redirect) {

		logger.debug(" 【 Controller 】- 【 AcctCtrl 】- 【 Registration 】-【 GET/POST 】- 开始运行  ");

		logger.debug(" 请求的参数req为 " + req.toString());

		ErrorRep err = null;
		String errMsg = "";

		try {

			acctServ.create(req);

			errMsg = "注册成功，请登录";
			err = ErrorRep.instance(true, errMsg);
			redirect.addFlashAttribute("err", err);

		} catch (Exception e) {
			errMsg = "注册失败";
			err = ErrorRep.instance(false, errMsg);
			redirect.addFlashAttribute("err", err);
			return "redirect:/user/registration";
		}

		return "redirect:/user/login";
	}

	@RequestMapping(value = "/login")
	public String login(HttpServletRequest req, Model model) {

		logger.debug(" 【 Controller 】- 【 Acct 】- 【 Login 】-【 GET/POST 】- 开始运行  ");

		ErrorRep err = null;
		String errMsg = "";

		try {

			// ------------------ 登录失败返回信息 ------------------
			String exceptionClassName = (String) req.getAttribute("shiroLoginFailure");
			// System.out.println();
			// String exception =
			if (UnknownAccountException.class.getName().equals(exceptionClassName)) {
				errMsg = "用户名不存在";
				err = ErrorRep.instance(false, errMsg);
			} else if (IncorrectCredentialsException.class.getName().equals(exceptionClassName)) {
				errMsg = "用户名/密码错误";
				err = ErrorRep.instance(false, errMsg);
			} else if (LockedAccountException.class.getName().equals(exceptionClassName)) {
				errMsg = "用户被锁定";
				err = ErrorRep.instance(false, errMsg);
			} else if (exceptionClassName != null) {
				errMsg = "其他错误";
				err = ErrorRep.instance(false, errMsg);
			}

			model.addAttribute("error", err);
			model.addAttribute("htmlTitle", htmlTitle);
			model.addAttribute("loginTitle", loginTitle);

		} catch (Exception e) {
			model.addAttribute("err", e.getMessage());
			return "error/500";
		}
		return "user/login";
	}

	@RequestMapping(value = "/editpass", method = RequestMethod.GET)
	public String editPass(@CurrentUser ShiroAcct curr, Model model) {

		logger.debug(" 【 Controller 】- 【 Acct 】- 【 EditPass 】-【 GET 】- 开始运行  ");

		try {

			// ------------------ 获取用户操作的 Menu ------------------
			List<AdmRes> menus = acctServ.queryMenuById(Integer.valueOf(curr.getId()));

			model.addAttribute("user", curr);
			model.addAttribute("menus", menus);
			model.addAttribute("htmlTitle", htmlTitle);
		} catch (Exception e) {
			model.addAttribute("err", e.getMessage());
			return "error/500";
		}
		return "user/editpass";
	}

	@RequestMapping(value = "/editpass", method = RequestMethod.POST)
	public String editPass(@CurrentUser ShiroAcct curr, PassReq req, RedirectAttributes redirect) {

		logger.debug(" 【 Controller 】- 【 Acct 】- 【 EditPass 】-【 POST 】- 开始运行  ");

		ErrorRep err = null;
		String errMsg = "";

		try {
			logger.debug(" 原密码及新密码为 " + req.toString());

			// ------------------ 获取用户操作的 Menu ------------------
			AdmAcct acct = AdmAcct.instance(curr);
			String pass = SecureUtil.initPass(acct.getPass(), acct.getSign());
			if (!pass.equals(curr.getPass())) {
				StormrageTechException.instance(ErrCons.CTRL_ERR, "原密码错误", StormrageTechException.ERR_APP,
						"【 AcctCtrl 】-【 EditPass 】");
				errMsg = "原密码错误";
				err = ErrorRep.instance(false, errMsg);
				redirect.addFlashAttribute("err", err);
				return "redirect:/user/editpass";
			}

			// ------------------ 获取用户操作的 Menu ------------------
			AdmAcctReq passReq = AdmAcctReq.instance(curr.getAcct(), req.getNpass(), null, null, null);
			acctServ.updatePass(passReq);

			// ------------------ 赋值 Model ------------------
			errMsg = "修改密码成功";
			err = ErrorRep.instance(false, errMsg);
			redirect.addFlashAttribute("err", err);

		} catch (Exception e) {
			errMsg = "修改密码失败";
			err = ErrorRep.instance(false, errMsg);
			redirect.addFlashAttribute("err", err);
			return "redirect:/user/editpass";
		}

		return "redirect:/user/editpass";
	}

}
